package com.ang.service;

import com.alibaba.fastjson.JSON;
import com.ang.base.WeChatAccessToken;
import com.ang.base.WeChatConstant;
import com.ang.base.WeChatUserInfo;
import com.ang.config.WeChatConfig;
import com.ang.domain.ParamObject;
import com.ang.utils.HttpUtils;
import com.ang.utils.MySerializable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.UUID;

/**
 * @author ssang
 * @date 2022-01-13 10:54
 */
@Service
public class WeChatLoginService {

    @Autowired
    WeChatConfig authWinxinConfig;

    /**
     * 获取第三方登录页面，即显示微信扫码页面的地址
     */
    public String getWeixinQRUrl() throws IOException {
        //String redirectUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";

        //处理一下回调地址
        String backUrl = null;
        try {
            String path = authWinxinConfig.getBackUrl();
            backUrl = URLEncoder.encode(path,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //生成随机的UUID，作为state，微信平台回调本地接口时，会携带此参数，可以校验此参数，可用于防止csrf攻击（跨站请求伪造攻击）
//        String state = UUID.randomUUID().toString();
//        redisService.setCacheObject(WeChatConstant.STATE_KEY,state);

        //利用state来传递对象参数
        ParamObject object = new ParamObject("1","tom","男",24);
        String state = MySerializable.getStrFromObj(object);

        //拼接跳转的扫码地址
        StringBuffer redirectUrl = new StringBuffer();
        redirectUrl.append(authWinxinConfig.getAuthorizeUrl())
                .append("?appid=").append(authWinxinConfig.getAppID())
                .append("&redirect_uri=").append(backUrl)
                .append("&scope=").append(WeChatConstant.SNSAPI_USERINFO)
                .append("&response_type=").append(WeChatConstant.RESPONSE_TYPE_CODE)
                .append("&state=").append(state)
                .append("#wechat_redirect");

        return redirectUrl.toString();
    }

    /**
     * 根据code获取token和openid
     */
    public WeChatAccessToken getAccessTokenByCode(String code){
        //https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
        StringBuffer tokenUrl = new StringBuffer();
        tokenUrl.append(authWinxinConfig.getTokenUrl())
                .append("?appid=").append(authWinxinConfig.getAppID())
                .append("&secret=").append(authWinxinConfig.getAppsecret())
                .append("&code=").append(code)
                .append("&grant_type=").append(WeChatConstant.AUTHORIZATION_CODE);

        String result = HttpUtils.get(tokenUrl.toString());
        System.out.println(result);
        WeChatAccessToken token = JSON.parseObject(result, WeChatAccessToken.class);

        return token;
    }

    /**
     * 根据token和openID获取用户信息
     */
    public WeChatUserInfo getWeixinUserInfo(WeChatAccessToken token){
        //https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID
        StringBuffer userInfoUrl = new StringBuffer();
        userInfoUrl.append(authWinxinConfig.getUserInfoUrl())
                .append("?access_token=").append(token.getAccess_token())
                .append("&openid=").append(token.getOpenid());

        String userStr = HttpUtils.get(userInfoUrl.toString());
        System.out.println(userStr);
        WeChatUserInfo weChartUserInfo = JSON.parseObject(userStr, WeChatUserInfo.class);

        return weChartUserInfo;
    }
}
